package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class AutoFillAspect {
    /**
     * 自动填充切面，用于自动填充实体对象的公共字段值
     */
    @Before("execution(* com.sky.mapper.*.*(..)) && @annotation(autoFill)")
    public void autoFill(JoinPoint joinPoint, AutoFill autoFill){
        log.info("自动填写字段");
        //获取mapper方法的参数:entity
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object entity = args[0];

        //准备要赋的值
        LocalDateTime now = LocalDateTime.now();
        Long currentUser = BaseContext.getCurrentId();

        //判断操作的类型
        Class<?> clazz = entity.getClass();
        if (autoFill.value() == OperationType.INSERT) {
            try{
                //是新增条件: 获取setCreateTime、setUpdateTime、setCreateUser、setUpdateUser四个方法
                Method setCreateTimeMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
                Method setUpdateTimeMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method setCreateUserMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
                Method setUpdateUserMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);

                //使用反射调用entity的对应方法,给属性赋值
                setCreateTimeMethod.invoke(entity,now);
                setUpdateTimeMethod.invoke(entity,now);
                setCreateUserMethod.invoke(entity,currentUser);
                setUpdateUserMethod.invoke(entity,currentUser);
            } catch (Exception e){
                e.printStackTrace();
            }
        } else {
            try {
                //是修改操作: 获取setUpdateTime、setUpdateUser两个方法
                Method setUpdateTimeMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method setUpdateUserMethod = clazz.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                //使用反射调用entity的对应方法,给属性赋值
                setUpdateTimeMethod.invoke(entity,now);
                setUpdateUserMethod.invoke(entity,currentUser);
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
